<template>
  <div  class="stock-out-management">
    <div style="display: flex;justify-content: space-between;">
      <div class="title">
        <div>角色列表</div>
      </div>
      <el-button type="primary" @click="handleAdd" style="margin-bottom: 10px">+ 新增</el-button>
    </div>
    

    <el-table :data="roleList" style="width: 100%">
      <el-table-column type="index" label="序号" width="70"></el-table-column>
      <el-table-column prop="moniker" label="角色名称"></el-table-column>
      <el-table-column prop="staffNames" label="角色人员合集">
        <template slot-scope="scope">
<!--          <el-tag v-for="(item, index) in scope.row.staffNames" :key="index">{{ item }}</el-tag>-->
          <span>{{scope.row.staffNames.join('、')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 合计信息 -->
    <div class="bottom-container">
      <div class="pagination-wrapper">
        <pagination :total="total" :page.sync="queryParams._page" :limit.sync="queryParams._limit"
                    @pagination="handleQuery"/>
      </div>
    </div>
    <el-dialog  :visible.sync="dialogVisible" :title="mode === 'add' ? '角色与权限新增' : '角色与权限编辑'"
               width="1200px" v-if="dialogVisible" append-to-body top="30px">
      <label>角色名称</label>
      <el-input v-model="roleName" placeholder="请输入角色名称" style="width: 300px;margin-left: 10px"></el-input>
      <el-tree
        :data="menuList"
        show-checkbox
        node-key="id"
        :default-expanded-keys="[1]"
        :props="defaultProps"
        @check-change="handleCheckChange"
        ref="permissionTree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRole">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import pagination from "@/components/Pagination/index.vue";
import {treeDataTranslate} from "@/utils/util";
import {menuList, roleDelete, roleList, roleMenu, roleMenuUpdate, roleSave} from "@/api/mgmt/sys/role";

export default {
  components: {
    pagination
  },
  data() {
    return {
      queryParams: {
        _page: 1,
        _limit: 10,
      },
      mode: '',
      roleList: [],
      total: 0,
      dialogVisible: false,
      roleName: '',
      defaultProps: {
        children: 'children',
        label: 'moniker'
      },
      menuList: [],
      roleMenu: [], //角色已有权限菜单
      currentRolePermissions: [],// 当前角色已有的权限 id 列表
      menuIds: [],
      updateId: '',
    };
  },
  computed: {},
  mounted() {
    this.handleQuery()
  },
  methods: {
    handleQuery() {
      this.getList();
    },
    getList() {
      roleList(this.queryParams).then(res => {
        this.roleList = res.list;
        this.total = res.total;
      })
    },
    resetQuery() {
      this.queryParams = {
        _page: 1,
        _limit: 10,
      };
      this.handleQuery();
    },
    handleAdd() {
      this.mode = 'add';
      this.dialogVisible = true;
      this.roleName = ''
      this.getMenu()
    },
    getMenu() {
      menuList().then(res => {
        this.menuList = treeDataTranslate(res.list, 'id', 'pid')
      })
    },
    getRoleMenu(id) {
      roleMenu(id).then(res => {
        this.currentRolePermissions = res.list.map(item => item.id);
        // console.log(this.currentRolePermissions)
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs.permissionTree.setCheckedKeys(this.currentRolePermissions)
        })
      })
    },
    getAllIds(obj) {
      let ids = [];
      if (obj.id !== undefined) {
        ids.push(obj.id);
      }
      if (obj.children && Array.isArray(obj.children)) {
        obj.children.forEach(child => {
          ids = ids.concat(this.getAllIds(child));
        });
      }
      return ids;
    },
    handleCheckChange(data, checked, indeterminate) {
      this.menuIds = this.getAllIds(data)
    },
    handleView(row) {
      this.mode = 'edit';
      this.roleName = row.moniker
      this.getMenu()
      this.getRoleMenu(row.id)
      this.updateId = row.id
    },
    saveRole() {
      if (this.mode === 'add') {
        const menuIds = this.menuIds
        const mgmtRoleEntity = {
          moniker: this.roleName,
          clinicId: this.$store.getters.clinicId,
        }
        let data = {
          menuIds,
          mgmtRoleEntity
        }
        roleSave(data).then(res => {
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.dialogVisible = false;
          this.handleQuery();
        })
      } else {
        const selectedKeys = this.$refs.permissionTree.getCheckedKeys();
        this.currentRolePermissions = [...new Set([...selectedKeys])];
        // console.log("更新后的权限 ID 列表:", this.currentRolePermissions);

        const menuIds = [...this.currentRolePermissions]
        const mgmtRoleEntity = {
          moniker: this.roleName,
          id: this.updateId,
          clinicId: this.$store.getters.clinicId,
        }
        let data = {
          menuIds,
          mgmtRoleEntity
        }
        roleMenuUpdate(data).then(res => {
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.dialogVisible = false;
          this.handleQuery();
        })
      }
    },
    closeDialog(value) {
      this.dialogVisible = false;
      if (value) {
        this.handleQuery();
      }
    },
    handleDelete(row) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        roleDelete(row.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.handleQuery();
        })
      }).catch(() => {
      })
    },
  }
};
</script>

<style scoped>
.stock-out-management {
  padding: 20px;
  box-sizing: border-box;
  background: #fff;
}

.query-form {
  margin-bottom: 20px;
}

.summary {
  margin-top: 20px;
  font-weight: bold;
}

.header-cell {
  text-align: center;
}

.title {
    padding-left: 10px;
    border-left: 4px solid #DC402B;
    margin-bottom: 22px;
  }
</style>
